package org.lex.ftp.queue;

import java.io.*;
import javax.swing.Icon;

import org.lex.ftp.FTP;
import org.lex.ftp.model.FTPModel;
import org.lex.ftp.util.FTPFileIconCache;
import org.lex.io.filesystem.FileNameUtilities;
import org.lex.net.ftp.IFTPFile;


/*
 * DownloadTask or UploadTask
 */
public abstract class XloadTask extends Task {
	protected String ftpPath = null;
	protected IFTPFile ftpFile = null;
	protected File file = null;

	/**
	 * @param ftpFile
	 *            ��Ҫ�����FTP�ļ�
	 * @param file
	 *            ��Ҫ����ı����ļ�ϵͳ���ļ�������Ŀ¼���ļ���
	 */
	public XloadTask(FTP app, String ftpPath, IFTPFile ftpFile, File file) {
		super(app);
		this.ftpPath = ftpPath;
		this.ftpFile = ftpFile;
		this.file = file;
	}

	protected Icon getFTPFileIcon(IFTPFile f) {
		// ftpFile
		if (this.hasChild())
			return FTPFileIconCache.getInstance().getFolderIcon();
		else
			return FTPFileIconCache.getInstance().getIcon(f);
	}

	protected Icon getFileIcon(File f) {
		// file
		if (this.hasChild())
			return FTPFileIconCache.getInstance().getFolderIcon();
		else
			return FTPFileIconCache.getInstance().getIcon(FileNameUtilities.getExtension(f.getName()));
	}

	protected InputStream openFTPInputStream() throws IOException {
		FTPModel model = this.app.getFTPExplorer().getFTPModel();
		String pwd = model.getCatalog();
		if (false == pwd.equals(ftpPath))
			model.setCatalog(ftpPath);
		return model.getFTPClient().get(ftpFile.getName());
	}

	protected OutputStream openFTPOutputStream() throws IOException {
		// handle file exist fule
		return null;
	}

	protected InputStream openFileInputStream() throws IOException {
		return null;
	}

	protected OutputStream openFileOutputStream() throws IOException {
		File dir = file.getParentFile();
		OutputStream out = null;
		if (false == dir.exists() || false == dir.isDirectory())
			dir.mkdirs();
		if (false == file.exists() || false == file.isFile()) {
			file.createNewFile();
			out = new FileOutputStream(file);
		} else {
			// TODO handle file exist rules here
		}
		return out;
	}
}
